<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="optionsData" :formData="form">
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="创建人"
          />
        </template>
        <template #bill_time="{ input, value }">
          <template v-if="props.type == '2'">
            <el-date-picker
              :modelValue="value"
              @update:modelValue="input"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择月"
            />
          </template>
          <template v-else>
            <WeekPicker :modelValue="value" @update:modelValue="input" />
          </template>
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #exchange_rate="{ row }">
      <div>{{ row.currency }} {{ formatNumber(row.exchange_rate) }}</div>
    </template>
    <template #operate="{ row }">
      <div class="flex flex-wrap items-center">
        <el-button
          link
          type="primary"
          @click="handleDetail(row.id)"
          v-hasPermi="[financeManageAuthList.initial_bills.details]"
        >
          详情
        </el-button>
        <el-button
          v-if="row?.reconcile_status == 0"
          link
          type="primary"
          @click="handleSubmit(row.id)"
          v-hasPermi="[financeManageAuthList.initial_bills.submit]"
        >
          提交
        </el-button>
      </div>
      <div class="flex flex-wrap items-center">
        <el-button link type="primary" @click="handleResult(row)"
          >下载导入结果</el-button
        >
        <el-dropdown @Command="(e) => handleCommand(e, row)">
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <template
                v-for="(item, index) in operateList[props.type]"
                :key="index"
              >
                <el-dropdown-item
                  v-if="
                    item?.isShow?.includes(row?.reconcile_status) &&
                    isPermission(item.permission)
                  "
                  :command="item.label"
                  >{{ item?.label }}
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
          <SvgIcon class="ml-[16px]" icon-class="more" />
        </el-dropdown>
      </div>
    </template>
  </VTable>
  <ApplyPayDialog
    v-model="applyPayVisible"
    :data="selectItem"
    @close="selectItem = {}"
    @refresh="refresh"
  />
  <ImportDialog
    :optionsData="optionsData"
    v-model="importVisible"
    :id="importId"
    :type="importType"
    @close="(importId = ''), (importType = '')"
    @refresh="refresh"
  />
  <detail
    v-model="detailDialog"
    :logistics_pay_number="logistics_pay_number"
    @close="logistics_pay_number = ''"
  />
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="finance.initial-bills"
    :business_id="logId"
    @close="logId = ''"
  />
  <ApplyPayment
    v-model="paymentDialog"
    :id="paymentId"
    :data="paymentData"
    @refresh="refresh"
    @close="
      paymentId = '';
      paymentData = {};
    "
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import XForm from "@/components/XForm/index.vue";
// import ApplyPayDialog from "../ApplyPayDialog/index.vue";
import detail from "@/views/finance-manage/bills-payment/detail/index.vue";
import Log from "@/components/Log/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { tipMessage } from "@/hooks/tool.js";
import WeekPicker from "../ImportDialog/components/weekPicker/index";
import {
  countryList,
  submitBills,
  cancelBills,
  downImportResult,
  tcBillPush,
  reverseApproved,
  getApplyPaymentGd,
} from "../../api/index";
import { formatNumber } from "@/utils/tool.js";
import ImportDialog from "../ImportDialog/index";
import { config_name } from "@/config/export.js";
import { tabName } from "../../data.js";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import { isPermission } from "@/hooks/permission.js";
import SvgIcon from "@/components/SvgIcon/index.vue";
import ApplyPayment from "../applyPayment/index";
const router = useRouter();
const { proxy } = getCurrentInstance();

const props = defineProps({
  optionsData: { type: Object, default: () => {} },
  type: { type: String, default: "" },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "submit_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  rowConfig: {
    height: 75,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "账单编号",
      minWidth: 135,
      field: "bill_number",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-link
                underline={false}
                type="primary"
                onClick={() => handleDetail(row.id)}
              >
                {row.bill_number}
              </el-link>
              <div>{`${row?.bill_year_month} ${row?.bill_ym_week}`}</div>
            </div>
          );
        },
      },
    },
    {
      title: "账单名称",
      width: 160,
      slots: {
        default: ({ row }) => {
          return (
            <el-link
              underline={false}
              type="primary"
              onClick={() => handleLink(row?.bill_file?.oss_path)}
            >
              <svg-icon icon-class="downloadicon" />
              <VText value={row?.bill_name} line={2} class="v-text-color" />
            </el-link>
          );
        },
      },
    },
    {
      title: "账单类型",
      width: 80,
      field: "bill_cycle_type_text",
    },
    {
      title: "物流商名称",
      width: 220,
      field: "logistics_name",
    },
    {
      title: "导入匹配信息",
      width: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span>
                导入<span class="text-[#3487FF]">{row.import_num || 0}</span>/
              </span>
              <span>
                成功<span class="text-[#3487FF]">{row.success_num || 0}</span>/
              </span>
              <span>
                警告<span class="text-[#3487FF]">{row.warning_num || 0}</span>/
              </span>
              <span>
                错误<span class="text-[#3487FF]">{row.error_num || 0}</span>
              </span>
            </div>
          );
        },
      },
    },
    { title: "物流账单金额/CNY", width: 160, field: "logistics_amount" },
    { title: "系统金额/CNY", width: 160, field: "system_amount" },
    { title: "差异金额/CNY", width: 160, field: "difference_amount" },
    {
      title: "币种汇率",
      width: 160,
      field: "exchange_rate",
      slots: { default: "exchange_rate" },
    },
    { title: "状态", width: 160, field: "audit_status_label" },
    { title: "申付金额", width: 160, field: "request_pay_amount" },
    { title: "付款金额", width: 160, field: "pay_amount" },
    {
      title: "人员",
      width: 400,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-[20px]  min-w-[80px]">
                  <span class="text-[var(--other-color-6)]">提交：</span>
                  {row?.submit_user || "-"}
                </div>
                <div>
                  <span class="text-[var(--other-color-6)]">审核：</span>
                  {row?.audit_user || "-"}
                </div>
              </div>
              <div class="flex">
                <div class="mr-[20px] min-w-[80px]">
                  <span class="text-[var(--other-color-6)]">申付：</span>
                  {row?.request_user || "-"}
                </div>
                <div>
                  <span class="text-[var(--other-color-6)]">付款：</span>
                  {row?.pay_user || "-"}
                </div>
              </div>
              <div>
                <span class="text-[var(--other-color-6)]">导入：</span>
                {row?.import_user || "-"}
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "时间",
      width: 420,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-[20px]  min-w-[180px]">
                  <span class="text-[var(--other-color-6)]">提交：</span>
                  {row.submit_time || "-"}
                </div>
                <div>
                  <span class="text-[var(--other-color-6)]">审核：</span>
                  {row.audit_time || "-"}
                </div>
              </div>
              <div class="flex">
                <div class="mr-[20px] min-w-[180px]">
                  <span class="text-[var(--other-color-6)]"> 申付：</span>
                  {row.request_time || "-"}
                </div>
                <div>
                  <span class="text-[var(--other-color-6)]">付款：</span>
                  {row.pay_time || "-"}
                </div>
              </div>
              <div>
                <span class="text-[var(--other-color-6)]">导入：</span>
                {row?.import_time || "-"}
              </div>
            </div>
          );
        },
      },
    },
    { title: "物流备注", width: 200, field: "logistics_remark" },
    { title: "财务备注", width: 200, field: "finance_remark" },
    {
      title: "原始账单文件",
      width: 200,
      field: "bill_name",
      slots: {
        default: ({ row }) => {
          return (
            <el-link
              underline={false}
              type="primary"
              onClick={() => handleLink(row?.original_bill_file?.oss_path)}
            >
              <svg-icon icon-class="downloadicon" />
              <VText
                value={row?.original_bill_file?.filename}
                line={2}
                class="v-text-color"
              />
            </el-link>
          );
        },
      },
    },
    {
      title: "操作",
      width: "160",
      fixed: "right",
      slots: { default: "operate" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        const { bill_time } = form;
        let obj = {
          ...form,
          bill_cycle_type: tabName?.[props.type] ?? "",
          bill_year_month: props.type == "2" ? bill_time : bill_time?.[0] ?? "",
          bill_ym_week: props.type == "2" ? undefined : bill_time?.[1] ?? "",
          bill_time: undefined,
        };
        return countryList({ ...obj, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const handleDetail = (id) => {
  router.push(`/finance-manage/initial-bills/detail?id=${id}`);
};

const handleLink = (_link) => {
  if (!_link) return;
  window.open(_link, "noopener", "noreferrer");
};

//提交
const handleSubmit = (id) => {
  handleSubmitReq(id);
};
const handleSubmitReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认提交 {id?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await submitBills({ id });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//下载导入结果
const handleResult = async (e) => {
  const { code, message } = await downImportResult({ id: e.id });
  if (code !== 200) return ElMessage.error(message);
  ElMessage.success("下载成功,请在导出中心查看!");
};

//导入
const importVisible = ref(false);
const importType = ref(null);
const handleImport = () => {
  importVisible.value = true;
  importType.value = tabName[props.type];
};

//编辑
const importId = ref(null);
const handleEdit = (_id) => {
  importId.value = _id.id;
  importVisible.value = true;
  importType.value = tabName[props.type];
};

//作废
const handleCancel = (e) => {
  const { id } = e;
  proxy?.confirm({
    title: "提示",
    content: <p>确认删除该条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await cancelBills({ id });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          if (data?.success_data?.length) {
            ElMessage.success({
              dangerouslyUseHTMLString: true,
              message: data.success_data.join("<br/>"),
            });
          }
          if (data?.fail_data?.length) {
            ElMessage.error({
              dangerouslyUseHTMLString: true,
              message: data.fail_data.join("<br/>"),
            });
          }
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//申请付款
// const applyPayVisible = ref(false);
// const selectItem = ref({});
// const handleApplyPay = (e) => {
//   applyPayVisible.value = true;
//   selectItem.value = e;
// };

//查看付款信息
const logistics_pay_number = ref("");
const detailDialog = ref(false);
const handelPaymentInfo = (item) => {
  if (!item.logistics_pay_number) return ElMessage.warning("暂无付款信息!");
  logistics_pay_number.value = item.logistics_pay_number;
  detailDialog.value = true;
};

//日志
const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const handleCommand = (e, row) => {
  const _item = operateList[props.type].find((n) => n.label === e);
  _item.fn?.(JSON.parse(JSON.stringify(row)));
};

//导出
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["initial_bill"],
    condition,
  });
};
const handleBatchSubmit = () => {
  let records = getTableSelect(tableRef.value);
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  handleSubmitReq(records);
};
const handleBatchSync = () => {
  let records = getTableSelect(tableRef.value);
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  proxy?.confirm({
    title: "提示",
    content: <p>确认同步 {records?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await tcBillPush({ id: records });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("同步成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleUnAudit = (e) => {
  const { id } = e;
  proxy?.confirm({
    title: "提示",
    content: <p>确认反审该条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await reverseApproved({ id });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          if (data?.success_data?.length) {
            ElMessage.success({
              dangerouslyUseHTMLString: true,
              message: data.success_data.join("<br/>"),
            });
          }
          if (data?.fail_data?.length) {
            ElMessage.error({
              dangerouslyUseHTMLString: true,
              message: data.fail_data.join("<br/>"),
            });
          }
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const paymentDialog = ref(false);
const paymentId = ref([]);
const paymentData = ref({});
const handleBatchPayment = async (e) => {
  // let records = getTableSelect(tableRef.value);
  let records = e?.id || null;
  // if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  try {
    const { data, code, message } = await getApplyPaymentGd({ id: records });
    if (code != 200) return ElMessage.warning(message);
    paymentId.value = records;
    paymentData.value = data || {};
    paymentDialog.value = true;
  } catch (error) {}
};
const actions = ref([
  {
    label: "批量提交",
    type: "primary",
    fn: handleBatchSubmit,
    permission: [financeManageAuthList.initial_bills.submit],
  },
  {
    label: "同步",
    fn: handleBatchSync,
    permission: [financeManageAuthList.initial_bills.sync],
  },
  // {
  //   label: "申请付款",
  //   fn: handleBatchPayment,
  //   permission: [financeManageAuthList.initial_bills.sync],
  // },
  {
    label: "导入",
    dkicon: "icon-Download",
    fn: handleImport,
    right: "true",
    permission: [financeManageAuthList.initial_bills.import],
  },
  {
    label: "导出",
    dkicon: "icon-Upload",
    right: "true",
    fn: handleExport,
    permission: [financeManageAuthList.initial_bills.export],
  },
]);

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "bill_number",
    placeholder: "账号编号",
    type: "input",
    ...publicStyle,
  },
  {
    field: "logistics_id",
    type: "select",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
    class: "select-wrapper-style",
    originOption: "map.logistics",
  },
  {
    field: "reconcile_status",
    type: "select",
    originOption: "reconcile_status",
    options: {
      placeholder: "状态",
      data: [
        { label: "全部", value: "" },
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
    style: { width: "140px" }
  },
  {
    field: "bill_time",
    label: "账单日期",
    slot: "bill_time",
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "100px" },
    select: [
      { label: "提交时间", value: "submit_time" },
      { label: "审核时间", value: "audit_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];

const operateList = {
  1: [
    {
      label: "编辑",
      fn: handleEdit,
      isShow: [0],
      permission: [financeManageAuthList.initial_bills.edit],
    },
    {
      label: "删除",
      fn: handleCancel,
      isShow: [0],
      permission: [financeManageAuthList.initial_bills.cancel],
    },
    {
      label: "反审",
      fn: handleUnAudit,
      isShow: [2],
      permission: [financeManageAuthList.initial_bills.unaudit],
    },
    {
      label: "日志",
      fn: handleLog,
      isShow: [0, 1, 2, 3, 4, 5, 6],
      permission: [financeManageAuthList.initial_bills.log],
    },
  ],
  2: [
    {
      label: "编辑",
      fn: handleEdit,
      isShow: [0],
      permission: [financeManageAuthList.initial_bills.edit],
    },
    {
      label: "删除",
      fn: handleCancel,
      isShow: [0],
      permission: [financeManageAuthList.initial_bills.cancel],
    },
    {
      label: "反审",
      fn: handleUnAudit,
      isShow: [2],
      permission: [financeManageAuthList.initial_bills.unaudit],
    },
    {
      label: "申请付款",
      fn: handleBatchPayment,
      isShow: [2, 6],
      permission: [financeManageAuthList.initial_bills.payment],
    },

    {
      label: "查看付款信息",
      fn: handelPaymentInfo,
      isShow: [3, 4],
      permission: [financeManageAuthList.initial_bills.checkpayment],
    },
    {
      label: "日志",
      fn: handleLog,
      isShow: [0, 1, 2, 3, 4, 5, 6],
      permission: [financeManageAuthList.initial_bills.log],
    },
  ],
};
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 80px) !important;
}
:deep(.v-text-color) {
  .v-text-content {
    color: #3486fe;
  }
}
</style>
